package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private SystemUserService systemUserService;

    @Override
    public CaptchaVo getCaptcha() {
        //1.创建验证码图片的工具类
        SpecCaptcha specCaptcha = new SpecCaptcha(130,48,4);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        //2.生成验证码图片的base64和验证码正确字符串
        String imgBase64 = specCaptcha.toBase64(); // [1 2 3 4 ]
        String codeString = specCaptcha.text();
        //3.正确字符串 + uuidkey + 有效时间存储到redis中
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString().replaceAll("-","");
        redisTemplate.opsForValue().set(key,codeString,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        //4.uuidkey + 验证码图片 -> CaptchaVo返回
        CaptchaVo captchaVo = new CaptchaVo(imgBase64,key);
        return captchaVo;
    }

    @Override
    /**
     * 用户登录方法
     *
     * @param loginVo 登录凭证对象，包含用户名、密码和验证码信息
     * @return 返回JWT令牌
     * @throws LeaseException 登录过程中发生异常时抛出
     */
    public String login(LoginVo loginVo) {
        // 检查登录凭证中的验证码文本是否为空
        if ((ObjectUtils.isEmpty(loginVo.getCaptchaCode()))) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        // 从Redis中获取验证码
        String codeString = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        // 检查验证码是否过期
        if (ObjectUtils.isEmpty(codeString)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        // 检查用户输入的验证码是否正确
        if (!codeString.equalsIgnoreCase(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        // 根据用户名查询用户信息
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(lambdaQueryWrapper);
        // 检查用户是否存在
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        // 计算用户输入的密码的MD5哈希值
        String password = DigestUtils.md5Hex(loginVo.getPassword());
        // 检查密码是否正确
        if (!systemUser.getPassword().equals(password)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        // 检查用户账号是否被禁用
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        // 登录成功，生成并返回JWT令牌
        return JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
    }
}
